package com.example.anpnovel.controller.business;

import com.example.anpapi.entity.dto.TxtNovelImportRequest;
import com.example.anpapi.entity.po.novelmodel.Chapter.Chapter;
import com.example.anpapi.entity.po.novelmodel.Novel.Novel;
import com.example.anpapi.entity.po.novelmodel.Novel.NovelStatus;
import com.example.anpapi.entity.po.novelmodel.Novel.NovelVisibility;
import com.example.anpapi.entity.vo.R;
import com.example.anpnovel.service.interfaces.ChapterService;
import com.example.anpnovel.service.interfaces.NovelService;
import com.example.anpnovel.util.TxtNovelParser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * TXT 小说导入业务
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/business/novel")
public class NovelTxtImportController {

    private static final Charset FILE_CHARSET = Charset.forName("GBK");

    @Autowired
    private final NovelService novelService;

    @Autowired
    private final ChapterService chapterService;

    /**
     * 从本地 TXT 文件导入小说与章节
     */
    @PostMapping("/importTxt")
    @Transactional(rollbackFor = Exception.class)
    public R<Map<String, Object>> importFromTxt(@RequestBody TxtNovelImportRequest request) {


        if (request == null || !StringUtils.hasText(request.getFilePath())) {
            return R.error("filePath 不能为空");
        }
        File txtFile = new File(request.getFilePath());
        if (!txtFile.exists() || !txtFile.isFile()) {
            return R.error("文件不存在：" + request.getFilePath());
        }

        try {
            Novel novelPayload = buildNovelFromTxt(txtFile);
            Novel novel = findOrCreateNovel(novelPayload);

            List<Chapter> chapters = TxtNovelParser.parseFile(txtFile, novel.getId(), null, FILE_CHARSET);
            if (chapters.isEmpty()) {
                return R.error("未识别到任何章节，请检查TXT内容格式");
            }

            chapterService.saveBatch(chapters);

            int addedWordCount = chapters.stream()
                    .mapToInt(chapter -> chapter.getWordCount() == null ? 0 : chapter.getWordCount())
                    .sum();
            updateNovelStats(novel, novelPayload, addedWordCount, chapters.size());

            Map<String, Object> response = new HashMap<>();
            response.put("novelId", novel.getId());
            response.put("title", novel.getTitle());
            response.put("author", novel.getAuthorName());
            response.put("chapterAdded", chapters.size());
            response.put("wordCountAdded", addedWordCount);

            return R.success(response, "TXT小说导入成功");
        } catch (IOException e) {
            log.error("TXT小说导入失败，filePath={}", request.getFilePath(), e);
            return R.error("TXT小说导入失败：" + e.getMessage());
        }
    }

    /**
     * 根据导入的小说信息判断是否存在并返回或创建新的小说记录
     */
    private Novel findOrCreateNovel(Novel candidate) {
        Novel novel = novelService.lambdaQuery()
                .eq(Novel::getTitle, candidate.getTitle())
                .eq(StringUtils.hasText(candidate.getAuthorName()), Novel::getAuthorName, candidate.getAuthorName())
                .last("limit 1")
                .one();
        if (novel != null) {
            return novel;
        }

        initializeNovelDefaults(candidate);
        novelService.save(candidate);
        return candidate;
    }

    /**
     * 根据本次导入结果更新小说的字数、章节数以及补全缺失的作者/简介信息
     */
    private void updateNovelStats(Novel novel, Novel novelPayload, int addedWords, int addedChapters) {
        int currentWords = novel.getWordCount() == null ? 0 : novel.getWordCount();
        int currentChapters = novel.getChapterCount() == null ? 0 : novel.getChapterCount();

        novel.setWordCount(currentWords + addedWords);
        novel.setChapterCount(currentChapters + addedChapters);

        if (!StringUtils.hasText(novel.getAuthorName()) && StringUtils.hasText(novelPayload.getAuthorName())) {
            novel.setAuthorName(novelPayload.getAuthorName());
        }
        if (!StringUtils.hasText(novel.getDescription()) && StringUtils.hasText(novelPayload.getDescription())) {
            novel.setDescription(novelPayload.getDescription());
        }

        novelService.updateById(novel);
    }

    /**
     * 解析 TXT 文件头部信息并构建带有默认值的 Novel 对象
     */
    private Novel buildNovelFromTxt(File file) throws IOException {
        Novel novel = new Novel();
        String title = file.getName();
        if (title.toLowerCase().endsWith(".txt")) {
            title = title.substring(0, title.length() - 4);
        }
        novel.setTitle(title.trim());

        String authorName = null;
        String description = null;
        boolean introNextLine = false;

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), FILE_CHARSET))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String trimmed = line.trim();
                if (!StringUtils.hasText(trimmed)) {
                    continue;
                }

                if (!StringUtils.hasText(authorName) && trimmed.startsWith("作者")) {
                    authorName = parseValueAfterColon(trimmed);
                    continue;
                }

                if (trimmed.contains("内容简介")) {
                    introNextLine = true;
                    continue;
                }

                if (introNextLine) {
                    description = trimmed;
                    break;
                }
            }
        }

        if (!StringUtils.hasText(authorName)) {
            authorName = "未知作者";
        }
        novel.setAuthorName(authorName);
        novel.setDescription(description == null ? "" : description);
        novel.setStatus(NovelStatus.DRAFT);
        novel.setVisibility(NovelVisibility.PUBLIC);
        initializeNovelDefaults(novel);
        return novel;
    }

    /**
     * 对小说数值型、布尔型字段以及作者ID、分类ID进行默认值初始化，避免数据库非空约束和后续统计出现空指针
     */
    private void initializeNovelDefaults(Novel novel) {
        if (novel.getAuthorId() == null) {
            // TXT 导入场景下没有绑定站内作者账号时，使用占位作者ID（根据实际业务可调整为系统默认作者）
            novel.setAuthorId(0L);
        }
        if (novel.getCategoryId() == null) {
            // TXT 导入暂未提供分类信息，使用占位分类ID，后续可在管理后台修改到真实分类
            novel.setCategoryId(0L);
        }
        if (novel.getWordCount() == null) {
            novel.setWordCount(0);
        }
        if (novel.getChapterCount() == null) {
            novel.setChapterCount(0);
        }
        if (novel.getReadCount() == null) {
            novel.setReadCount(0);
        }
        if (novel.getLikeCount() == null) {
            novel.setLikeCount(0);
        }
        if (novel.getFavoriteCount() == null) {
            novel.setFavoriteCount(0);
        }
        if (novel.getRating() == null) {
            novel.setRating(BigDecimal.ZERO);
        }
        if (novel.getIsVip() == null) {
            novel.setIsVip(Boolean.FALSE);
        }
        if (novel.getPrice() == null) {
            novel.setPrice(BigDecimal.ZERO);
        }
    }

    /**
     * 提取以冒号分隔的字段值，适配中英文冒号
     */
    private String parseValueAfterColon(String line) {
        String[] split = line.split("[：:]", 2);
        if (split.length == 2) {
            return split[1].trim();
        }
        return line.replace("作者", "").trim();
    }

}

